package com.xbq.exceleditor.ui

import android.app.AlertDialog
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.gyf.immersionbar.ktx.immersionBar
import com.xbq.exceleditor.R
import com.xbq.exceleditor.adapter.MyDocumentAdapter
import com.xbq.exceleditor.bean.event.DeleteDocumentEvent
import com.xbq.exceleditor.bean.event.NewDocumentEvent
import com.xbq.exceleditor.bean.viewmodel.MyDocumentViewModel
import com.xbq.exceleditor.databinding.ActivityMyDocumentBinding
import com.xbq.exceleditor.databinding.DlgDocumentOperateBinding
import com.xbq.exceleditor.db.ExcelDatabase
import com.xbq.exceleditor.ui.excel.ExcelActivity
import com.xbq.exceleditor.utils.ensureVip
import com.xbq.xbqsdk.component.activity.VBActivity
import com.xbq.xbqsdk.component.recyleview.LinearSpaceDecoration
import com.xbq.xbqsdk.util.ShareFileUtils
import com.xbq.xbqsdk.util.click.onDebouncedClick
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

/**
 * Author: liaohaiping
 * Time: 2020-10-30
 * Description:
 */
@AndroidEntryPoint
class MyDocumentActivity :
    VBActivity<ActivityMyDocumentBinding>() {

    val viewModel:MyDocumentViewModel by viewModels()
    @Inject
    lateinit var db: ExcelDatabase
    @Inject
    lateinit var adapter: MyDocumentAdapter
    override fun useEventBus(): Boolean {
        return true
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.adview.init("mydocuments",this)
        immersionBar {
            statusBarView(R.id.statusbar)
        }
        binding.btnBack.onDebouncedClick { finish() }

        initRecylerView()
        initData()

    }

    private fun initRecylerView() {
        binding.doclist.let {
            it.adapter = adapter
            it.layoutManager = LinearLayoutManager(this)
            it.addItemDecoration(LinearSpaceDecoration(4f))
            adapter.setOnItemClickListener { ad, view, position ->
                val item = adapter.getItem(position)
                ExcelActivity.startEdit(item)
            }
            adapter.setOnItemLongClickListener { ad, view, position ->
                val item = adapter.getItem(position)
                BottomSheetDialog(this).apply {
                    val dlgBinding = DlgDocumentOperateBinding.inflate(layoutInflater, null, false)
                    setContentView(dlgBinding.root)
                    dlgBinding.btnShare.onDebouncedClick {
                        dismiss()
                        ensureVip("shareDocument"){
                            ShareFileUtils.shareFile(context, item.xlsxPath)
                        }
                    }
                    dlgBinding.btnDelete.onDebouncedClick {
                        dismiss()
                        AlertDialog.Builder(this@MyDocumentActivity)
                            .setMessage("确认要删除？")
                            .setPositiveButton(R.string.confirm){dlg,which->
                                dlg.dismiss()
                                lifecycleScope.launch {
                                    db.docDao().delete(item)
                                    com.blankj.utilcode.util.FileUtils.delete(item.path)
                                    com.blankj.utilcode.util.FileUtils.delete(item.xlsxPath)
                                    adapter.remove(item)
                                }
                            }
                            .setNegativeButton(R.string.cancel){dlg,which-> dlg.dismiss() }
                            .show()

                    }
                    dlgBinding.btnCancel.onDebouncedClick { dismiss() }
                    setCanceledOnTouchOutside(true)
                    show()
                }
                true
            }
        }
        binding.smartRefresh.let {
            it.setEnableRefresh(false)
            it.setOnLoadMoreListener {
                lifecycleScope.launch {
                    val list = viewModel.findNextPage()
                    it.finishLoadMore()
                    if (list.isEmpty()) {
                        it.setEnableLoadMore(false)
                    } else {
                        adapter.addData(list)
                    }
                }
            }
        }
    }

    private fun initData() {
        lifecycleScope.launch {
            val list = viewModel.findFirstPage()
            if (list.size > 0) {
                binding.smartRefresh.setEnableLoadMore(true)
                adapter.setList(list)
            } else {
                binding.smartRefresh.setEnableLoadMore(false)
                adapter.setEmptyView(R.layout.recycle_no_data)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNewDocument(event: NewDocumentEvent) {
        adapter.addData(event.data)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDocumentDelete(event: DeleteDocumentEvent) {
        val data = adapter.data.firstOrNull { it.id == event.data.id }
        data?.let { adapter.remove(it) }
    }
}